package com.project.interceptor;

import com.project.annotation.IgnoreToken;
import com.project.bean.UserBean;
import com.project.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class SysInterceptor implements HandlerInterceptor {
    /**
     * 获取参数
     *
     * @param request
     * @param filedName
     * @return
     */
    public static String getParam(HttpServletRequest request, String filedName) {
        String param = request.getParameter(filedName);
        if (StringUtils.isEmpty(param)) {
            param = request.getHeader(filedName);
        }
        return param;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1：从 http 请求头获取请求接口
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        //2：检查是否有IgnoreToken注释，有则跳过认证
        if (method.isAnnotationPresent(IgnoreToken.class)) {
            IgnoreToken loginToken = method.getAnnotation(IgnoreToken.class);
            if (loginToken.required()) {
                return true;
            }
        }
        //从header中获取token
        UserBean userBean = JwtUtil.verifierJwt(getParam(request, "token"));
        if (null != userBean) {
            return true;
        }
        response.getWriter().print("tokenError");
        return false;
    }

}
